package com.flame.shapeville.controller;

import com.flame.shapeville.bean.Task;
import com.flame.shapeville.bean.User;
import com.flame.shapeville.enums.SceneStyle;
import com.flame.shapeville.factory.BeanFactory;
import com.flame.shapeville.service.ExerciseService;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;

import java.io.IOException;

/**
 * Controller responsible for managing task-related views and logic.
 * <p>
 * This class handles loading and displaying exercises based on the current task,
 * and manages navigation actions like returning to home or showing score details.
 *
 * @author Flame Dev Team
 * @version 1.0
 * @since 2025-05-03
 */
public class TaskController implements JfController {

    /**
     * Label displaying the current task name.
     */
    @FXML
    private Label taskName;

    /**
     * Container for the task content.
     */
    @FXML
    private StackPane taskNode;

    /**
     * Parent container for the score view.
     */
    @FXML
    private Parent score;

    /**
     * Controller for the score view component.
     */
    @FXML
    private ScoreController scoreController;

    /**
     * The current task being displayed.
     */
    private Task task;

    /**
     * Service for managing exercise data.
     */
    private ExerciseService exerciseService;

    /**
     * Path to FXML files for tasks.
     */
    private final static String TASK_PATH = "/static/fxml/component/task/";

    /**
     * Navigates back to the main scene.
     */
    @FXML
    private void home() {
        SceneController.setSceneStyle(SceneStyle.MAIN);
    }

    /**
     * Initializes the controller with user and task data.
     */
    @Override
    public void init() {
        User user = (User) BeanFactory.getBean("user");
        task = (Task) BeanFactory.getBean("curTask");
        exerciseService = (ExerciseService) BeanFactory.getBean("exerciseService");

        taskName.setText(task.getName());
        loadExercise();
    }

    /**
     * Loads the appropriate exercise FXML based on the current task style.
     */
    private void loadExercise() {
        String fxmlPath = TASK_PATH + task.getStyle().name().toLowerCase() + ".fxml";
        FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlPath));
        try {
            taskNode.getChildren().setAll((Node) loader.load());
            ((JfController) loader.getController()).init();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Shows the score panel and updates it with the latest task scores.
     */
    @FXML
    private void showScore() {
        scoreController.updateTaskScore();
        score.setVisible(true);
        score.setDisable(false);
    }
}
